﻿using System.Net;
using FileTransfer.Client.Upload;

namespace FileTransfer.Client.Model;

public class ProgressableStreamContent : StreamContent
{
    private readonly HttpContent _content;
    private readonly ProgressListenerDelegate _progressListener;

    public ProgressableStreamContent(HttpContent content, ProgressListenerDelegate progressCallback)
        : base(new MemoryStream())
    {
        _content = content;
        _progressListener = progressCallback;
        CopyHeaders();
    }

    private void CopyHeaders()
    {
        foreach (var header in _content.Headers)
        {
            Headers.TryAddWithoutValidation(header.Key, header.Value);
        }
    }

    protected override async Task SerializeToStreamAsync(Stream stream, TransportContext? context)
    {
        var contentStream = await _content.ReadAsStreamAsync();
        var totalLength = _content.Headers.ContentLength ?? -1;

        var buffer = new byte[8192];
        long bytesWritten = 0;

        while (true)
        {
            var readSize = await contentStream.ReadAsync(buffer);
            if (readSize <= 0)
                break;

            await stream.WriteAsync(buffer.AsMemory(0, readSize));
            bytesWritten += readSize;

            _progressListener.Invoke(bytesWritten, totalLength);
        }

        await stream.FlushAsync();
    }

    protected override bool TryComputeLength(out long length)
    {
        if (_content.Headers.ContentLength.HasValue)
        {
            length = _content.Headers.ContentLength.Value;
            return true;
        }

        length = -1;
        return false;
    }
}
